package org.example;

import java.io.*;
import java.net.Socket;
import java.util.concurrent.TimeUnit;

public class ClientObject {

    static Person sendObj = new Person("scy");
//    static String sendObj = "我是客户端,Abc123";

    public static void main(String[] args) throws IOException {

        System.out.println("该程序为连接并发送Person对象到服务器," +
                "\n请在args指定待连接的服务器.例如java org.example.ClientObject scy1" +
                "\n如果不指定服务器,默认就是localhost");
        String SERVER;
        if (args.length == 0) {
            SERVER = "localhost";
        } else {
            SERVER= args[0];
        }


        Socket socket = new Socket(SERVER, 30000);
        System.out.println(socket);
        OutputStream outputStream = socket.getOutputStream();
        InputStream inputStream = socket.getInputStream();


        // 写线程 (向服务器写数据)
        new Thread(new Runnable() {

            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);

            @Override
            public void run() {
                try {
                    int i = 1;
                    while (true) {
                        if (i >= 5) {
                            System.out.println("开始跳出循环了,马上shutdownOutput了");
//                            socket.shutdownOutput();
                            break;
                        }
                        i++;

                        objectOutputStream.writeObject(sendObj);
                        TimeUnit.SECONDS.sleep(8);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();


        //读线程 (读取服务器发过来的数据)
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
                    while (true) {
                        Object object = objectInputStream.readObject();
                        System.out.println("client receive:" + object);
                        System.out.println("获取到对象的类型:" + object.getClass());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }, "readerThread4Client").start();

    }
}
